$(function() {
	var userInfo = {
		initDate: function(e){
			$(e).datetimepicker({//选择年月日
				format: 'yyyy-mm-dd',
				minView: 2, 
				weekStart: 1,
				autoclose: 1,
				todayHighlight: 1,
				startView: 2,
				forceParse: 0
			}).on('hide',function(){
				$("#userGrid").reloadSearchTable();
			});
		},
		initGrid: function(){
			$('#userGrid').jqGrid({
				url : "/user/list/page",
				colModel : [
					{name : "id",index : "id",key : true,hidden : true},
					{name : "loginName",label : "登录名称"},
					{name : "nickName",label : "用户昵称"},
					{name : "email",label : "电子邮件"}, 
					{name : "phone",label : "手机号"},
					{name : "createTime",label : "创建时间",searchoptions: {dataInit:userInfo.initDate}},
					{name : "lastUpdateTime",label : "最后登录时间",searchoptions: {dataInit:userInfo.initDate}},
					{name : "lastLoginIp",label : "最后登录ip"}, 
					{name : "roleId",label : "默认角色id",hidden:true}, 
					{name : "isOpen",label : "登录状态",
						stype: 'select',
						searchoptions: {dataUrl:'',buildSelect: function () {
							var html = '<select class="form-control">';
							html += '<option value="">全部</option>';
							html += '<option value="true">已启用</option>';
							html += '<option value="false">已禁用</option>';
							html += '</select>';
							return html;
						}},
						formatter:function(value, options, row){
							if (value) {
								return '<input name="isOpen"  data-id="'+row.id+'" type="checkbox" class="make-switch" checked="checked">';
							}else{
								return '<input name="isOpen"  data-id="'+row.id+'" type="checkbox" class="make-switch" >';
							}
						}
					}
					],
					search : true,
					autowidth: true,
					height: "100%",
					pager : "#userGridPager",
					gridComplete: function(){
						$('#userGrid input[name="isOpen"]').bootstrapSwitch({
							onText: "已启用",
							offText: "已禁用",
							onColor: "success",
							offColor: "default",
							size: "mini",
							onSwitchChange: function(event, state){
								var id = $(this).attr('data-id');
								$.post("/user/save",{id:id,isOpen:state},function(){
									$("#userGrid").reloadTable();
								});
							}
						});
					}
			});
			$('#userGrid').jqGrid('filterToolbar');
			userInfo.initButton();
		},
		initButton: function(){
			$("#sys_user_add").click(function(){
				userInfo.initDialog(true);
			});
			$("#sys_user_edit").click(function(){
				var id = $('#userGrid').jqGrid('getGridParam', 'selrow');
				if (!id) {
					toastr.warning("请选择要修改的用户");
					return false;
				} 
				userInfo.initDialog(true, id);
			});
			$("#sys_user_view").click(function(){
				var id = $('#userGrid').jqGrid('getGridParam', 'selrow');
				if (!id) {
					toastr.warning("请选择要查看的用户");
					return false;
				} 
				userInfo.initDialog(false,id);
			});
			$("#sys_user_del").click(function(){
				userInfo.delUser();
			});
			$("#sys_user_role_config").click(function(){
				debugger;
				var id = $('#userGrid').jqGrid('getGridParam', 'selrow');
				var row = $("#userGrid").jqGrid("getRowData",id);
				if (!id) {
					toastr.warning("请选择要设置角色的用户");
					return false;
				} 
				var rAjax = $.post("/role/getRolesByUserId", {userId: id});
				var dAjax = $.get("/user/getDefaultRoleId", {userId: id});
				$.when(rAjax,dAjax).done(function(roleData,defaultData){
					var roles = roleData[0];
					var defaultRole = defaultData[0];
					BootstrapDialog.show({
						title : '用户信息',
						size : BootstrapDialog.SIZE_NORMAL,
						backdrop : true,
						message : $('<div></div>').load('/fashion/user/role/config'),
						onshown: function() {
							$.each(roles,function(index,node){
								var option = "";
								if(node.id == defaultRole.roleId){
									option = '<option value="{0}" selected>{1}</option>'.format(node.id,node.roleName);
								}else{
									option = '<option value="{0}" >{1}</option>'.format(node.id,node.roleName);
								}
								$("#sys_user_role_config_form [name='roleIds']").append(option);
							});
							$("#loginName").val(row.loginName);
							$('#sys_user_role_config_form [name="id"]').val(row.id);
							$('#sys_user_role_config_form [name="roleIds"]').selectpicker('refresh');
						},
						buttons : [
						{
							id : 'button',
							label : '确定',
							cssClass : 'btn-success',
							action : function(dialog) {
								var object = $("#sys_user_role_config_form").serializeObject();
								$.post("/user/save/roles",object,function(resultData){
									toastr.result(resultData,function(){
										dialog.close();
										$("#userGrid").reloadTable();
									});
								});
							}
						}, {
							label : '取消',
							action : function(dialog) {
								dialog.close();
							}
						}]
					});
				});
			});
			
			$("#sys_user_photo_config").click(function(){
				var id = $('#userGrid').jqGrid('getGridParam', 'selrow');
				if (!id) {
					toastr.warning("请选择要设置头像的用户");
					return false;
				} 
				var cropper = null;
				BootstrapDialog.show({
					title : '用户头像',
					size : BootstrapDialog.SIZE_NORMAL,
					backdrop : true,
					message : $('<div></div>').load('/fashion/user/photo/config'),
					onshown: function(dialog) {
						require([ 'cropper' ], function(Cropper) {
							var image = document.querySelector('#user_picture_protrait');
							cropper = new Cropper(image, {
								viewMode : 3,
								aspectRatio : 1,
								dragMode : 'move',
								autoCropArea : 1,
								restore : false,
								guides : false,
								cropBoxMovable : false,
								cropBoxResizable : false,
								toggleDragModeOnDblclick : false,
								minContainerWidth : 160,
								minContainerHeight : 160
							});
							$("#user_photo").change(function(e) {
								var files = e.target.files;
								if (files && files.length > 0) {
									var file = files[0];
									if (URL) {
										cropper.replace(URL.createObjectURL(file));
									} else if (FileReader) {
										reader = new FileReader();
										reader.onload = function(e) {
											cropper.replace(reader.result);
										};
										reader.readAsDataURL(file);
									}
								}
							});
						});	
					},
					buttons : [
					{
						id : 'button',
						label : '确定',
						cssClass : 'btn-primary',
						action : function(dialog) {
							if(cropper != null){
								var canvas = cropper.getCroppedCanvas();
								var base64url = canvas.toDataURL('image/jpeg');
								$.post('/user/save',{id:id,picture:base64url},function(data){
									toastr.result(data,function(){
										$("#userGrid").reloadTable();
										dialog.close();
									});
								});
							}
						}
					}, {
						label : '取消',
						action : function(dialog) {
							dialog.close();
						}
					}]
				});
			});
		},
		initDialog:function(isEdit,id){
			var rAjax = $.get("/role/list");
			var uAjax = $.get("/user/list/"+id);
			var rsAjax = $.get("/role/getRoleIdsByUserId",{userId:id});
			$.when(rAjax,uAjax,rsAjax).done(function(rData,uData,rIdData){
				var roles = rData[0];
				var user = uData[0];
				var roleIds = rIdData[0];
				BootstrapDialog.show({
					title : '用户信息',
					size : BootstrapDialog.SIZE_NORMAL,
					backdrop : true,
					message : $('<div></div>').load('/fashion/user/save'),
					onshown: function(dialog) {
						$.each(roles,function(index,node){
							var option = '<option value="{0}">{1}</option>'.format(node.id,node.roleName);
							$("#user_form [name='roleIds']").append(option);
						});
						$('#user_form [name="roleIds"]').selectpicker('refresh'); 
						user.roleIds = roleIds;
						if(!isEdit){
							$("#user_form").readonly();
							$('#user_form [name="isOpen"]').bootstrapSwitch('readonly',true);  
							dialog.getButton('button').disable();
						}else{
							userInfo.validateUser();
						}
						$("#user_form").initForm(user);
						
					},
					buttons : [ {
						id : 'button',
						label : '确定',
						cssClass : 'btn-primary',
						action : function(dialog) {
							userInfo.saveUser(function(){
								dialog.close();
							});
						}
					}, {
						label : '取消',
						action : function(dialog) {
							dialog.close();
						}
					} ]
				});
			});
		},
		saveUser: function(callback){
			var bootstrapValidator = $('#user_form').data('bootstrapValidator');
			bootstrapValidator.validate();
			if (bootstrapValidator.isValid()) {
				var json = $('#user_form').serializeObject();
				$.ajax({
					url : '/user/save/roles',
					type : 'post',
					async:false,
					dataType : 'json',
					data : json,
					success : function(data) {
						toastr.result(data,function(){
							if($.isFunction(callback)){
								callback();
							}
							$("#userGrid").reloadTable();
						});
					},
					error : function(data) {
						toastr.error("系统内部错误");
					}
				});
			}
		},
		delUser: function(){
			// 获取选中行的id
			var uid = $('#userGrid').jqGrid('getGridParam', 'selrow');
			if (uid == null) {
				toastr.error("请选择要删除的用户");
				return false;
			} 
			$.confirm("确定要删除该用户吗",function(){
				$.post("/user/delete", {id : uid}, function() {
					$("#userGrid").trigger("reloadGrid");
				});
			});
		},
		//验证
		validateUser: function(){
			$("#user_form").bootstrapValidator({
				feedbackIcons : {// 根据验证结果显示的各种图标
					valid : 'glyphicon glyphicon-ok',
					invalid : 'glyphicon glyphicon-remove',
					validating : 'glyphicon glyphicon-refresh'
				},
				fields : {
					nickName : {
						validators : {
							notEmpty : {
								message : '昵称不能为空'
							},
							stringLength : {// 检测长度
								min : 1,
								max : 16,
								message : '长度必须在1-6之间'
							}
						}
					},
					password : {
						validators : {
							notEmpty : {
								message : '密码不能为空'
							}
						}
					},
					email : {
						validators : {
							notEmpty : {
								message : '邮箱地址不能为空'
							},
							emailAddress : {
								message : '请输入正确的邮箱地址'
							}
						}
					},
					phone : {
						validators : {
							notEmpty : {
								message : '手机号不能为空'
							},
							digits : {
								message : '该值只能包含数字。'
							},
							stringlength : {
								min : 11,
								max : 11,
								message : '请输入11位手机号码'
							},
							regexp : {
								regexp : /^1[3|5|7|8]{1}[0-9]{9}$/,
								message : '请输入正确的手机号码'
							}
						}
					}
				}
			});
		}
	}	
	userInfo.initGrid();
});